<template>
  <div class="map-wrapper">
    <div id="map-container" style="width: 100%; height: 80vh"></div>
    <div v-if="currentSpot" class="spot-selector" :class="{ expanded: isExpanded }">
      <!-- 左侧景点栏保持不变 -->
    </div>
    <!-- 图例 -->
    <div class="map-legend">
      <div v-for="(type, key) in SPOT_TYPES" :key="key" class="legend-item">
        <span class="legend-marker" :style="{ background: type.color }">{{ type.icon }}</span>
        <span>{{ type.name }}</span>
      </div>
    </div>
    <!-- 修改为浮动式详情面板 -->
    <div v-if="selectedSpot" class="spot-details" :style="detailPosition">
      <div class="details-content">
        <h2>{{ selectedSpot.name }}</h2>
        <img v-if="selectedSpot.details?.image" :src="selectedSpot.details.image" alt="景点图片" />
        <p v-if="selectedSpot.details?.description">{{ selectedSpot.details.description }}</p>
        <p v-else>暂无详情描述</p>
        <button class="close-btn" @click="selectedSpot = null">×</button>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { loadAMap } from '@/utils/amapLoader'
import { scenicSpots,SPOT_TYPES,PATH_TYPES } from '@/mock/scenicSpots'

//响应式变量
const isExpanded = ref(false)
const map = ref(null) // 将地图实例存储为响应式变量
const currentSpot = ref(null)
const route = useRoute()
const selectedSpot = ref(null)
const detailPosition = ref({
  top: 'auto',
  bottom: 'auto',
  left: 'auto',
  right: 'auto'
})
const highlightedMarker = ref(null) //存储当前高亮标记

//函数
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

const focusOnSpot = (subSpot) => {
  if (!map.value) {
    console.error('地图实例未初始化')
    return
  }
  
  // 清除之前的高亮
  if (highlightedMarker.value) {
    resetMarkerStyle(highlightedMarker.value)
    highlightedMarker.value = null
  }
  
  const [lng, lat] = virtualToReal(subSpot.x, subSpot.y)
  console.log('移动至坐标:', lng, lat)
  
  // 使用更精确的匹配方式
  const targetPos = new AMap.LngLat(lng, lat)
  const tolerance = 0.00001 // 更小的容差范围
  
  map.value.panTo([lng, lat])
  map.value.setZoom(30, false)
  
  // 高亮当前标记
  const markers = map.value.getAllOverlays('marker')
  markers.forEach(m => {
    const pos = m.getPosition()
    // 使用高德地图的equals方法进行精确比较
    if (targetPos.equals(pos, tolerance)) {
      // 使用新的高亮效果
      m.setContent(createHighlightMarkerContent(subSpot))
      highlightedMarker.value = m
    }
  })
  
  setDetailPosition(lng, lat)
}

// 专门的高亮标记内容
const createHighlightMarkerContent = (spot) => {
  const markerSize = 18 // 比普通标记稍大
  const highlightColor = '#FFD700' // 金色
  const highlightBorder = '#FFA500' // 橙色边框
  
  return `
    <div style="display:flex; flex-direction:column; align-items:center;">
      <div style="
        width:${markerSize}px; 
        height:${markerSize}px; 
        background:${highlightColor};
        border-radius:50%;
        display:flex;
        justify-content:center;
        align-items:center;
        color:#FFFFFF;
        font-size:14px;
        font-weight:bold;
        border:3px solid ${highlightBorder};
        box-shadow:0 2px 8px rgba(0,0,0,0.4);
        animation: pulse 1s infinite alternate;
      "></div>
      <div style="
        margin-top:10px;
        padding:3px 10px;
        background:white;
        color:#333;
        font-size:14px;
        font-weight:bold;
        border-radius:4px;
        box-shadow:0 2px 4px rgba(0,0,0,0.3);
        border:1px solid ${highlightBorder};
      ">${spot.name}</div>
    </div>
  `
}

//创建标记内容的函数
const createMarkerContent = (spot, isHighlighted = false) => {
  const typeInfo = SPOT_TYPES[spot.type] || SPOT_TYPES.SCENIC
  const markerSize = isHighlighted ? 20 : 16
  const markerColor = isHighlighted ? '#FFD700' : typeInfo.color
  
  return `
    <div style="display:flex; flex-direction:column; align-items:center;">
      <div style="
        width:${markerSize}px; 
        height:${markerSize}px; 
        background:${markerColor};
        border-radius:50%;
        display:flex;
        justify-content:center;
        align-items:center;
        color:white;
        font-size:12px;
        border:2px solid white;
        box-shadow:0 2px 4px rgba(0,0,0,0.3);
      ">${typeInfo.icon}</div>
      <div style="margin-top:4px; padding:2px 6px; background:white; border-radius:4px;">
        ${spot.name}
      </div>
    </div>
  `
}


// 新增：重置标记样式
const resetMarkerStyle = (marker) => {
  const pos = marker.getPosition()
  const realPos = [pos.lng, pos.lat]
  const spot = findSpotByPosition(realPos)
  if (spot) {
    marker.setContent(createMarkerContent(spot))
  }
}

// 新增：根据位置查找景点
const findSpotByPosition = ([lng, lat]) => {
  if (!currentSpot.value) return null
  
  // 检查主景点
  const mainSpotPos = virtualToReal(currentSpot.value.center.x, currentSpot.value.center.y)
  if (Math.abs(mainSpotPos[0] - lng) < 0.0001 && Math.abs(mainSpotPos[1] - lat) < 0.0001) {
    return { ...currentSpot.value.center, name: currentSpot.value.name }
  }
  
  // 检查子景点
  return currentSpot.value.subSpots.find(sub => {
    const subPos = virtualToReal(sub.x, sub.y)
    return Math.abs(subPos[0] - lng) < 0.0001 && Math.abs(subPos[1] - lat) < 0.0001
  })
}

// 根据点击位置设置详情面板位置
const setDetailPosition = (lng, lat) => {
  // 获取地图容器尺寸
  const container = document.getElementById('map-container')
  const rect = container.getBoundingClientRect()
  
  // 将经纬度转换为屏幕坐标
  const pixel = map.value.lngLatToContainer([lng, lat])
  
  // 计算最佳显示位置
  const position = { top: 'auto', bottom: 'auto', left: 'auto', right: 'auto' }
  
  if (pixel.y < rect.height / 2) {
    position.top = `${pixel.y + 20}px`  // 如果在上面半区，详情显示在下方
  } else {
    position.bottom = `${rect.height - pixel.y + 20}px`  // 如果在下面半区，详情显示在上方
  }
  
  if (pixel.x < rect.width / 2) {
    position.left = `${pixel.x + 20}px`  // 如果在左半区，详情显示在右侧
  } else {
    position.right = `${rect.width - pixel.x + 20}px`  // 如果在右半区，详情显示在左侧
  }
  
  detailPosition.value = position
}


function showDetails(spot) {
  selectedSpot.value = spot
}

// 虚拟坐标范围定义
const VIRTUAL_RANGE = {
  minX: 0,
  maxX: 1000,
  minY: 0,
  maxY: 1000
};

// 实际映射到的地理范围（北京某区域）
const REAL_BOUNDS = {
  minLng: 116.397,  // 最小经度
  maxLng: 116.405,  // 最大经度
  minLat: 39.915,   // 最小纬度
  maxLat: 39.920    // 最大纬度
};

// 坐标转换函数
function virtualToReal(x, y) {
  const lng = REAL_BOUNDS.minLng + 
    (x - VIRTUAL_RANGE.minX) * (REAL_BOUNDS.maxLng - REAL_BOUNDS.minLng) / 
    (VIRTUAL_RANGE.maxX - VIRTUAL_RANGE.minX);
  
  const lat = REAL_BOUNDS.maxLat - 
    (y - VIRTUAL_RANGE.minY) * (REAL_BOUNDS.maxLat - REAL_BOUNDS.minLat) / 
    (VIRTUAL_RANGE.maxY - VIRTUAL_RANGE.minY);
  
  return [lng, lat];
}


// 路由参数

const spotId = route.query.id // 从路由中获取景点 ID




onMounted(async () => {
  try {
    // 获取当前景点数据
    const spotData = scenicSpots[spotId]
    if (!spotData) {
      console.error('未找到对应的景点数据')
      return
    }
    currentSpot.value = spotData

    // 加载高德地图 SDK
    const AMap = await loadAMap()

    // 初始化地图
    map.value = new AMap.Map('map-container', {
      zoom: 17,
      center: virtualToReal(spotData.center.x, spotData.center.y),
      viewMode: '2D',
      showIndoorMap: false,
      zoomEnable: true,
      dragEnable: true,
      rotateEnable: false,
      pitchEnable: false,
      layers: [],  // 不加载任何图层
      mapStyle: 'amap://styles/normal',  // 使用普通样式
      features: []  // 不显示任何要素
    })

    // 添加主景点标记
    const mainMarker = new AMap.Marker({
      position: virtualToReal(spotData.center.x, spotData.center.y),
      content: createMarkerContent({ 
        ...spotData.center, 
        name: spotData.name 
      }),
      offset: new AMap.Pixel(-15, -15) // 调整主景点偏移量
    })
    map.value.add(mainMarker)

    // 添加子景点标记
    spotData.subSpots.forEach((subSpot) => {
      const subMarker = new AMap.Marker({
        position: virtualToReal(subSpot.x, subSpot.y),
        content: createMarkerContent(subSpot),
        offset: new AMap.Pixel(-14, -10) // 使用统一尺寸计算
      })
      //显示景点信息
      subMarker.on('click', () => {
        selectedSpot.value = subSpot
        focusOnSpot(subSpot)
        // 清除其他矩形的高亮状态
        map.value.getAllOverlays('polygon').forEach((polygon) => {
          polygon.setOptions({
            strokeColor: '#f5f5f5', // 恢复默认边框颜色
            fillColor: '#87ceeb', // 恢复默认填充颜色
            fillOpacity: 0.3, // 恢复默认填充透明度
          });
        });
        // 设置当前矩形为高亮状态
        rectangle.setOptions({
          strokeColor: '#7ab8cc', // 高亮边框颜色
          fillOpacity: 0.5, // 增加填充透明度
        });
      })

      map.value.add(subMarker)

      // 为子景点添加矩形区域
      const offset = subSpot.offset; // 偏移量，控制矩形的大小

      // 计算矩形的四个顶点
      const path = [
        virtualToReal(subSpot.x - offset, subSpot.y - offset), // 左上角
        virtualToReal(subSpot.x + offset, subSpot.y - offset), // 右上角
        virtualToReal(subSpot.x + offset, subSpot.y + offset), // 右下角
        virtualToReal(subSpot.x - offset, subSpot.y + offset), // 左下角
      ];

      // 创建矩形区域
      const rectangle = new AMap.Polygon({
        path, // 矩形的顶点数组
        strokeColor: '#f5f5f5', // 边框颜色
        strokeWeight: 2, // 边框宽度
        strokeOpacity: 0.8, // 边框透明度
        fillColor: '#87ceeb', // 填充颜色
        fillOpacity: 0.3, // 填充透明度
      })
      // 将矩形添加到地图
      map.value.add(rectangle);

      // 鼠标悬停效果
      rectangle.on('mouseover', () => {
        rectangle.setOptions({
          strokeColor: '#7ab8cc', // 高亮边框颜色
          fillOpacity: 0.5, // 增加填充透明度
        });
      });

      rectangle.on('mouseout', () => {
        rectangle.setOptions({
        strokeColor: '#f5f5f5', // 恢复默认边框颜色
        fillOpacity: 0.3, // 恢复默认填充透明度
        });
      });
    })

    // 增强版边线绘制
    spotData.edges.forEach((edge) => {
      const fromSpot = spotData.subSpots.find(s => s.id === edge.from)
      const toSpot = spotData.subSpots.find(s => s.id === edge.to)

      if (fromSpot && toSpot) {
        const pathType = PATH_TYPES[edge.type] || PATH_TYPES.WALKWAY
        const line = new AMap.Polyline({
          path: [
            virtualToReal(fromSpot.x, fromSpot.y),
            virtualToReal(toSpot.x, toSpot.y)
          ],
          strokeColor: pathType.color,
          strokeWeight: pathType.weight,
          strokeStyle: pathType.dash ? 'dashed' : 'solid',
          strokeOpacity: 0.8,
          lineJoin: 'round'
        })

        map.value.add(line)
      }
    })
  
  

  map.value.on('zoomchange', () => {
    const zoomLevel = map.value.getZoom();

    spotData.subSpots.forEach((subSpot, index) => {
      const rectangle = map.value.getAllOverlays('polygon')[index]; // 获取对应的矩形
      if (zoomLevel < 19) {
        rectangle.hide(); // 缩放级别小于 15 时隐藏矩形
      } else {
        rectangle.show(); // 缩放级别大于等于 15 时显示矩形
      }
    });
  });

    // 调整视图以显示所有点
    map.value.setFitView()
  } catch (error) {
    console.error('加载高德地图失败:', error)
  }
})
</script>

<style scoped>
/* 增强地图容器样式 */
.map-wrapper {
  position: relative;
  width: 100%;
  height: 80vh;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.spot-selector {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  width: 200px;
  transition: all 0.3s ease;
}
.main-spot {
  padding: 12px 15px;
  font-weight: bold;
  color: #333;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.main-spot:hover {
  background: #f5f5f5;
}

.arrow {
  font-size: 12px;
  transition: transform 0.3s;
}

.arrow.rotated {
  transform: rotate(180deg);
}

.sub-spots-wrapper {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.spot-selector.expanded .sub-spots-wrapper {
  max-height: 400px; /* 根据实际内容调整 */
  overflow-y: auto;
}

.sub-spot {
  padding: 10px 15px;
  color: #555;
  cursor: pointer;
  transition: all 0.2s;
}

.sub-spot:hover {
  background: #e6f7ff;
  color: #1890ff;
}

.sub-spot:not(:last-child) {
  border-bottom: 1px solid #f0f0f0;
}

/* 景点详情 */
.spot-details {
  position: absolute;
  z-index: 999;
  max-width: 300px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.details-content {
  padding: 15px;
  position: relative;
}

.details-content h2 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #333;
}

.details-content img {
  width: 100%;
  max-height: 150px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.details-content p {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.close-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
  padding: 0 5px;
}

.close-btn:hover {
  color: #333;
}
/* 类型图例 */
.map-legend {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background: rgba(255,255,255,0.9);
  padding: 10px;
  border-radius: 4px;
  z-index: 999;
}
.legend-item {
  display: flex;
  align-items: center;
  margin: 5px 0;
}
.legend-marker {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  text-align: center;
  line-height: 20px;
  margin-right: 8px;
  font-size: 12px;
}

</style>